#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 /**
  * Definition for singly-linked list.
  * struct ListNode {
  *     int val;
  *     ListNode *next;
  *     ListNode() : val(0), next(nullptr) {}
  *     ListNode(int x) : val(x), next(nullptr) {}
  *     ListNode(int x, ListNode *next) : val(x), next(next) {}
  * };
  */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        ListNode* tail, * cur;
        cur = tail = head;
        for (int i = 0; i < k; ++i)
        {
            if (tail == nullptr)
                return head;
            tail = tail->next;
        }
        ListNode* prev = nullptr;
        while (cur != tail)
        {
            ListNode* Next = cur->next;
            cur->next = prev;
            prev = cur;
            cur = Next;
        }
        head->next = reverseKGroup(tail, k);
        return prev;
    }
};

